import React, { useState, useEffect } from 'react';
import { Divider, message } from "antd";
import { FireOutlined, LikeOutlined } from "@ant-design/icons";
import request from '../../services/request';
import styles from './styles.module.less';

const CardCom = ({
                     title = '',
                     icon = <></>,
                     describe = '',
                     id = '',
                     likeCount = 0,
                     hotCount: initialHotCount = 0, // 重命名参数为 initialHotCount
                     isLiked = false,
                 }) => {
    const [liked, setLiked] = useState(isLiked);
    const [count, setCount] = useState(likeCount);
    const [hotCount, setHotCount] = useState(initialHotCount); // 使用 initialHotCount

    useEffect(() => {
        setLiked(isLiked);
        setCount(likeCount);
        setHotCount(initialHotCount);
    }, [isLiked, likeCount, initialHotCount]);

    useEffect(() => {
        setCount(likeCount);
        setHotCount(initialHotCount);
    }, [likeCount, initialHotCount]);

    const handleLikeClick = async (event) => {
        event.stopPropagation();
        !liked ? message.success('Like success') : message.success('UnLike success');
        setCount(prevCount => liked ? prevCount - 1 : prevCount + 1);
        setLiked(prevLiked => !prevLiked);
        const res = await request({
            url: '/tools/like',
            method: 'post',
            data: {
                'like': !liked ? 0 : 1,
                'toolId': id,
            }
        });
    };

    return (
        <div className={styles.card}>
            <div className={styles.image}>
                {icon}
            </div>
            <div className={styles.card_info}>
                <span title={title}>{title}</span>
                <p title={describe}>{describe}</p>
            </div>
            <Divider className={styles.divider}/>
            <p className={styles.but}>
                <span onClick={handleLikeClick} style={{ color: liked ? 'red' : 'black', cursor: 'pointer' }}>
                    <LikeOutlined/> {count}
                </span>
                <FireOutlined style={{ marginLeft: '10px' }}/> {hotCount}
            </p>
        </div>
    );
};

export default CardCom;
